// pages/guest/store/store.js
var util = require("../../../utils/util.js")
const db=wx.cloud.database();
var app = getApp()
const _ = db.command


var moveFlag = true;// 判断执行滑动事件
var startX, endX;  //接触开始和结束x坐标
var moveFlag = true;//确保移动方向为首次


Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: null,
    active:'TuinaData',
    currentSelected:'TuinaData',
    listData:[],
    currentClick: 1,   
  },
 
  onSearch(e){
      console.log(e.detail)
      if(e.detail==''){

      }else{
        wx.navigateTo({
          url: './afterSearch/afterSearch?value='+e.detail,
        })
      }
  },
  onChange(e){
       this.value=e.detail
  },
  onLoad: function (options) {
    let that = this
    if (app.userDate.userInfo == null) {
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }else{
      that.getFavorActivity();
      that.getListData();
    }
  },

  getFavorActivity:function(){
    let that =this
    let currentDate =  util.formatDateTime(new Date())
    console.log(currentDate)
    db.collection('favourActivity').where(
      _.and([{
        startDate:_.lte(currentDate)
      },{
        endDate:_.gt(currentDate)
      }])
    )
    .get().then(res=>{
      // console.log(data)
      that.setData({
        imgUrls:res.data
      })
    })
  },
  getCartsData:function(e){
    wx.showLoading()
      console.log(e.currentTarget.dataset.id)
      console.log(e.currentTarget.dataset.type)
      let that = this
      let type = e.currentTarget.dataset.type
      let id = e.currentTarget.dataset.id

      // wx.setStorage({
      //   key:"CartsData",
      //   data:"value"
      // })
      db.collection('CartsData').where({
        UserID:app.userDate.userInfo.userPhone,
        CartsID:id
      }).get().then(res=>{
        console.log(res.data[0])
        if(res.data[0]!=undefined){
          wx.showToast({
            title: '商品已加入订单了哦~',
            icon:'none'
          })
          wx.hideLoading()
        }else{
          db.collection('CartsData').add({
            data:{
              UserID:app.userDate.userInfo.userPhone,
              className:type,
              CartsID:id,
              // GoodsName:name,
              // GoodsPrice:price,
              // GoodsImage:img,
              // GoodsNum:num,
              // checked:false,
              // date:util.formatDateTime(new Date())
            }
        }).then(res => {
          console.log(res)
          if(res.errMsg== "collection.add:ok"){
              wx.showToast({
                title: '成功添加至订单',
              })
              wx.hideLoading()
          }else{
            wx.showToast({
              title: '添加失败',
              icon:'/images/icon/defeat.png'
            })
          }
        })
        .catch(console.error)
        }
      })


   

    
      // if(type == 'tuina'){
      //   db.collection('TuinaData').where({
      //     TuinaID:id
      //   }).field({
      //     TuinaName:true,
      //     TuinaPrice:true,
      //     TuinaImage:true

      //   }).get().then(res=>{
      //     console.log(res.data[0])
      //     let type = "技师"
      //     let num = 1
      //     that.addCartsData(type,id,res.data[0].TuinaName,res.data[0].TuinaPrice,res.data[0].TuinaImage,num)
      //     wx.hideLoading()
      //   })
      // }else if(type == 'medic'){
      //   db.collection('MedicineData').where({
      //     MedicID:id
      //   }).field({
      //     MedicImage:true,
      //     MedicName:true,
      //     MedicPrice:true,
      //     MedicSurplus:true
      //   }).get().then(res=>{
      //     console.log(res.data[0])
          
      //     let type = "药品"
      //     that.addCartsData(type,id,res.data[0].MedicName,res.data[0].MedicPrice,res.data[0].MedicImage,res.data[0].MedicSurplus)
      //     wx.hideLoading()
      //   })
      // }else{
      //   db.collection('SidelineData').where({
      //     SidelineID:id
      //   }).field({
      //     SidelineName:true,
      //     SidelineImage:true,
      //     SidelinePrice:true
      //   }).get().then(res=>{
      //     console.log(res.data[0])
          
      //     let type = "其他"
      //     let num = 1

      //     that.addCartsData(type,id,res.data[0].SidelineName,res.data[0].SidelinePrice,res.data[0].SidelineImage,num)
      //     wx.hideLoading()
      //   })
      // }
      
  },
  // addCartsData:function(type,id,name,price,img,num){
  //     db.collection('CartsData').add({
  //         data:{
  //           UserID:'15707254047',//app.userDate.userInfo.userPhone,
  //           className:type,
  //           CartsID:id,
  //           GoodsName:name,
  //           GoodsPrice:price,
  //           GoodsImage:img,
  //           GoodsNum:num,
  //           checked:false,
  //           date:util.formatDateTime(new Date())
  //         }
  //     }).then(res => {
  //       console.log(res)
  //       if(res.errMsg== "collection.add:ok"){
  //           wx.showToast({
  //             title: '添加成功',
  //           })
  //       }else{
  //         wx.showToast({
  //           title: '添加失败',
  //           icon:'/images/icon/defeat.png'
  //         })
  //       }
  //     })
  //     .catch(console.error)
  // },

  //屏幕滑动事件
  //触摸开始
  touchStart: function (e) {
    // console.log("触摸开始")
    startX = e.touches[0].pageX;
    moveFlag = true;
  },


  touchMove: function (e) {
    // console.log("移动")
    var that = this
    endX = e.touches[0].pageX;
    if (moveFlag) {
      if (endX - startX > 100) {
        // console.log("左滑");
        that.moveright();
        moveFlag = false;
      }
      if (startX - endX > 100) {
        // console.log("右滑");
        that.moveleft();
        moveFlag = false;
      }
    }
  },

  touchEnd: function (e) {
    // console.log("触摸结束")
    moveFlag = true; // 回复滑动事件 
  },

  moveleft() {
    var that = this;
    let currentPage = that.data.currentClick
    if (currentPage >= 3) {
      wx.showToast({
        title: '滑动到最右了哦~',
        icon: "none"
      })
    } else {
      currentPage += 1
      console.log(currentPage)
      if(currentPage==1){
        that.setData({
          currentClick: currentPage,
          currentSelected:'TuinaData',
          active:'TuinaData',
          // listData:[]//清空list数组，避免渲染先出现格式后显示数据
        });
        that.getListData();
      }else if(currentPage==2){
        that.setData({
          currentClick: currentPage,
          currentSelected:'MedicineData',
          active:'MedicineData',
          // listData:[]//清空list数组，避免渲染先出现格式后显示数据
        });
        that.getListData();
      }else{
        that.setData({
          currentClick: currentPage,
          currentSelected:'SidelineData',
          active:'SidelineData',
          // listData:[]//清空list数组，避免渲染先出现格式后显示数据
        });
        that.getListData();
      }
    }
  },
  moveright() {
    var that = this;
    let currentPage = that.data.currentClick
    if (currentPage <= 1) {
      wx.showToast({
        title: '滑动到最左了哦~',
        icon: "none"
      })
    } else {
      currentPage -= 1
      // activelist:['TuinaData','MedicineData','SidelineData']
console.log(currentPage)
      if(currentPage==1){
        that.setData({
          currentClick: currentPage,
          currentSelected:'TuinaData',
          active:'TuinaData',
          // listData:[]//清空list数组，避免渲染先出现格式后显示数据
        });
        that.getListData();
      }else if(currentPage==2){
        that.setData({
          currentClick: currentPage,
          currentSelected:'MedicineData',
          active:'MedicineData',
          // listData:[]//清空list数组，避免渲染先出现格式后显示数据
        });
        that.getListData();
      }else{
        that.setData({
          currentClick: currentPage,
          currentSelected:'SidelineData',
          active:'SidelineData',
          // listData:[]//清空list数组，避免渲染先出现格式后显示数据
        });
        that.getListData();
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideTabBar({
      success: function () {
        console.log("隐藏Tabbar")
        app.onTabBar('user');
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onClick(ev){
    console.log(ev);
    this.setData({
      currentSelected:ev.detail.name,
      listData:[]//清空list数组，避免渲染先出现格式后显示数据
    });
    this.getListData();
  },

  getListData(){
    console.log("金融")
    let that =this
    if(that.data.currentSelected=='MedicineData'){
      db.collection(that.data.currentSelected).where({
        MedicSurplus: _.gt(0)
      }).get().then((res) => {
        console.log(res);
        that.setData({
          listData: res.data
        })
      })
    }else{
    db.collection(that.data.currentSelected).where({IsServiceable:true}).get().then((res) => {
      console.log(res);
      that.setData({
        listData: res.data
      })
    })}
  },

  
  handleTuinaDetail(ev) {
    //console.log(ev)
    let id = ev.target.dataset.id;
    wx.navigateTo({
      url: '/pages/guest/store/tuinaDetail/tuinaDetail?id=' + id
    })
   },
  handleMedicDetail(ev) {
    let id = ev.target.dataset.id;
    wx.navigateTo({
      url: '/pages/guest/store/medicDetail/medicDetail?id=' + id
    })
  }, handleSidelineDetail(ev) {
    let id = ev.target.dataset.id;
    wx.navigateTo({
      url: '/pages/guest/store/sidelineDetail/sidelineDetail?id=' + id
    })
  },
  gotoorder:function(){
    wx.navigateTo({
      url: '../store/order/order',
    })
  }

})